package com.dc.util;

import com.dc.ro.UrlRO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class DownloadUtil {

    /**
     * 文件打成压缩包下载
     * url 链接以及名称
     * fileName 下载框默认显示的文件名
     */
    public void downloadFile(List<UrlRO> url, String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (!CollectionUtils.isEmpty(url)) {
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            try {
                // 文件的名称
                String downloadFilename = fileName + ".zip";
                // 转换中文否则可能会产生乱码
                downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
                // 指明response的返回对象是文件流
                response.setContentType("application/octet-stream");
                // 设置在下载框默认显示的文件名
                response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);

                // 将文件打成压缩包并下载
                for (UrlRO urls : url) {
                    zos.putNextEntry(new ZipEntry(urls.getName()));
                    HttpURLConnection conn = (HttpURLConnection) new URL(urls.getUrl()).openConnection();
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    BufferedInputStream fis = null;
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        fis = new BufferedInputStream(conn.getInputStream());
                    }
                    byte[] buffer = new byte[1024];
                    int r = 0;
                    if (null != fis) {
                        while ((r = fis.read(buffer)) != -1) {
                            zos.write(buffer, 0, r);
                        }
                        fis.close();
                    }
                }
            } catch (Exception e) {
                log.error("下载文件失败", e);
            } finally {
                zos.flush();
                zos.close();
            }
        }

    }
}
